<template>
  <div class="fixed-header">
    <van-sticky>
      <div class="topdropdown">
        <van-dropdown-menu>
          <van-dropdown-item v-model="searchObj.value1" :options="option1" title="店铺" @change="storeChange"/>
          <van-dropdown-item v-model="searchObj.value2" :options="option2" title="订单状态" @change="payChange"/>
        </van-dropdown-menu>
        <div class="dropdownLeft" v-if="searchObj.value1"></div>
        <div class="dropdownRight" v-if="searchObj.value2"></div>
      </div>
      <div class="searchBox">
        <van-search
            v-model="params.keyword"
            :placeholder="placeholder"
            @search="handleSearch"
            @update:model-value="handleInput">
          <template #right-icon>
            <div class="search-confirm" @click.stop="handleSearch">
              <span style="margin-right: 10px;height: 24px;">|</span>
              <span class="search-text">搜索</span>
            </div>
          </template>
        </van-search>
        <div class="condition">
          <van-field v-model="params.startTime" readonly name="datePicker" placeholder="请选择开始时间"
                     @click="timekai('startTime')" style="width:40% ;cursor: pointer;" input-align="center"/>
          <van-field v-model="params.endTime" readonly name="datePicker" placeholder="请选择结束时间"
                     @click="timekai('endTime')" style="width:40% ;cursor: pointer;" input-align="center"/>
        </div>
        <div class="condition condition2" v-if="showStats">
          <span class="stats-tag">
            <span class="stats-label">累计充值金额：</span>
            <span class="stats-value">{{totalAmount}}</span>
          </span>
          <span class="stats-tag">
            <span class="stats-label">累计充值币数：</span>
            <span class="stats-value">{{totalCoins}}</span>
          </span>
        </div>
      </div>
    </van-sticky>
  </div>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载"
              finished-text="没有更多数据了"
              :finished="finished" @load="getdata">
      <!-- <DeviceList :list="list" :mark="mark"></DeviceList> -->
      <div style="padding: 0 10px;">
        <div class="grid-content" v-for="(item,index) in list" :key="index">
          <div style="padding: 10px;">
            <div class="flexbetween margin-b-12">
              <span class="storeTitle">订单号：{{ item.orderId }}</span>
              <van-tag type="warning" size="large" v-if="item.payState==0">待支付</van-tag>
              <van-tag type="success" size="large" v-if="item.payState==1">已支付</van-tag>
              <van-tag type="danger" size="large" v-if="item.payState==3">订单提交失败</van-tag>
              <van-tag type="danger" size="large" v-if="item.payState==4">退款中</van-tag>
              <van-tag type="danger" size="large" v-if="item.payState==5">已退款</van-tag>
              <van-tag type="danger" size="large" v-if="item.payState==6">退款失败</van-tag>
            </div>
            <div class="flex">
              <p class="margin-t-0 margin-b-12 hideText" style="width: 48%;">
								<span class="storeZi">
									用户：{{ item.nickname }}
								</span>
              </p>
              <p class="margin-t-0 margin-b-12 hideText" style="width: 50%;">
								<span class="storeZi">
									设备编码：{{ item.deviceNumber }}
								</span>
              </p>
            </div>
            <div class="flex">
              <p style="margin: 0;width: 48%;" class="hideText">
								<span class="storeZi">
									店铺：{{ item.storeName }}
								</span>
              </p>
              <p style="margin: 0;width: 50%;" class="hideText">
								<span class="storeZi">
									下单时间：{{ item.createTime2 }}
								</span>
              </p>
            </div>
          </div>
          <div class="divider"></div>
          <div class="grid-content-bottom">
            <p>金额：{{ item.amount }}</p>
            <div v-if="item.refundStatus">
              <button class="refund" @click="refunds(item)">退款</button>
            </div>
          </div>
        </div>
      </div>
    </van-list>
  </van-pull-refresh>
  <!-- 时间选择 -->
  <van-popup v-model:show="showPicker" destroy-on-close position="bottom" safe-area-inset-bottom round>
    <van-date-picker v-model="currentDate" @confirm="onConfirm" @cancel="showPicker = false"/>
  </van-popup>
</template>
<script setup>
import {
  ref,
  onMounted,
  reactive
} from "vue";
import {
  showConfirmDialog,
  showToast
} from 'vant';
import {
  getUserid
} from '@/utils/auth';
import {
  deviceRechargeRecordList,
  deviceRechargeRefund,
  getuserordersumapi
} from '@/api/order';
import {
  StoresList
} from '@/api/deviceRechargeConfig';

// const mark = ref('order')
const placeholder = ref('请输入用户昵称搜索');
var option1 = reactive([]);


// const option2 = [{
// 	text: '全部',
// 	value: ''
// }, {
// 	text: '待支付',
// 	value: 1
// }, {
// 	text: '已支付',
// 	value: 2
// }, {
// 	text: '订单提交失败',
// 	value: 3
// }, {
// 	text: '退款中',
// 	value: 4
// }, {
// 	text: '已退款',
// 	value: 5
// }, ];

const option2 = [{
  text: '全部',
  value: ''
}, {
  text: '微信',
  value: 0
}, {
  text: '支付宝',
  value: 1
}];

const searchObj = ref({
  value1: '',
  value2: ''
});

const loading = ref(false);
const finished = ref(false);
const error = ref(false);
// 下拉刷新状态
const refreshing = ref(false);
const showStats = ref(false); // 新增showStats变量

const totalAmount = ref(0); // 累计金额
const totalCoins = ref(0);  // 累计币数

const getTodayString = () => {
	const now = new Date();
	const year = now.getFullYear();
	const month = (now.getMonth() + 1).toString().padStart(2, '0');
	const day = now.getDate().toString().padStart(2, '0');
	return `${year}-${month}-${day}`;
};

const params = ref({
  size: 10,
  pages: 1,
  userId: getUserid(),
  keyword: '',
  payState: '',
  rechargeType:'',
  storeId: '',
  startTime: getTodayString(),
	endTime: getTodayString(),
});
const list = reactive([]);

onMounted(() => {
  getstore();
  getdata();
});
const getdata = async (isRefresh = false) => {
  loading.value = false;
  try {
    // 防止重复请求
    if (loading.value && !isRefresh) return;
    // 重置错误状态
    error.value = false;
    // 设置加载状态
    loading.value = true;

    const response = await deviceRechargeRecordList(params.value);
    const records = response.data.records || [];
    // 新增：格式化时间
    const formattedRecords = records.map(item => ({
      ...item,
      // 添加格式化后的时间字段（保留原始 createTime）
      createTime: formatISODate(item.createTime)
    }));
    // 如果是刷新操作，替换而不是追加数据
    if (isRefresh) {
      list.splice(0, list.length, ...formattedRecords);
    } else {
      list.push(...formattedRecords);
    }

    // 更新分页状态
    finished.value = records.length < params.value.size;
    params.value.pages += 1;
  } catch (err) {
    //console.error('获取数据失败', err);
    error.value = true;
    finished.value = false; // 确保可以重试

    // 如果是刷新操作需要保留刷新状态
    if (!isRefresh) {
      refreshing.value = false;
    }
  } finally {
    loading.value = false;
    // 如果是刷新操作，需要特殊处理
    if (isRefresh) {
      refreshing.value = false;
    }
  }
};


// 完善后的统计方法
const getuserordersum = async () => {
  try {
    // 使用与列表相同的查询参数
    const statsParams = {
      userId: params.value.userId,
      keyword: params.value.keyword,
      storeId: params.value.storeId,
      rechargeType: params.value.rechargeType,
      startTime: params.value.startTime,
      endTime: params.value.endTime
    };

    const response = await getuserordersumapi(statsParams);
    if (response.status === 200) {
      totalAmount.value = response.data.totalAmount || 0;
      totalCoins.value = response.data.totalCoins || 0;
    }
  } catch (err) {
    console.error('获取统计信息失败', err);
    showToast('获取统计信息失败');
  }
};





// 下拉刷新处理
const onRefresh = () => {
  // 立即清空列表
  list.splice(0, list.length);

  // 重置分页参数
  params.value.pages = 1;
  params.value.keyword = '';
  params.value.rechargeType = '';


  // 重置状态
  finished.value = false;
  loading.value = false;
  refreshing.value = true;
  error.value = false;

  // 直接调用 getdata，而不是等待列表自动触发
  getdata(true); // 传入 true 表示是刷新操作
  getuserordersum(); // 新增统计调用
};

// const handleSearch = (item) => {
//   showStats.value = true; // 搜索时显示统计信息
//   list.splice(0, list.length);
//   params.value.pages = 1;
//   finished.value = false;
//   getdata(true);
// };

const handleInput = () => {
  showStats.value = false; // 输入时隐藏统计信息
};

// 输入框搜索
const handleSearch = (item) => {
  list.splice(0, list.length);
  // 重置分页参数
  params.value.pages = 1;
  // params.value.startTime = '';
  // params.value.endTime = '';
  // 重置状态
  finished.value = false;
  loading.value = false;
  error.value = false;
  showStats.value = true; // 搜索时显示统计信息
  getdata(true);

  getuserordersum();
};
// 商店下拉列表
const getstore = async () => {
  const userId = {
    userId: getUserid(),
  }
  try {
    const response = await StoresList(userId);
    const records = response.data || [];
    option1 = [{
      text: "全部",
      value: ''
    }, ...records.map((item) => ({ // 展开原数组
      text: item.storeName,
      value: item.id,
    }))];
  } catch (err) {
    //console.error('获取数据失败', err);
  }
}; //订单状态下拉选择
const payChange = (state) => {
  if (state == 0) {
    params.value.rechargeType = 0;
  } else if (state == 1) {
    params.value.rechargeType = 1;
  } else {
    params.value.rechargeType = state;
  }
  searchObj.value2 = state;
  // params.value.startTime = '';
  // params.value.endTime = '';
  params.value.pages = 1;

  finished.value = false;
  loading.value = false;
  refreshing.value = true;
  error.value = false;

  // 直接调用 getdata，而不是等待列表自动触发
  getdata(true); // 传入 true 表示是刷新操作
  getuserordersum(); // 新增统计调用
};
const storeChange = (id) => {
  params.value.storeId = id;

  params.value.pages = 1;
  // params.value.startTime = '';
  // params.value.endTime = '';

  finished.value = false;
  loading.value = false;
  refreshing.value = true;
  error.value = false;

  // 直接调用 getdata，而不是等待列表自动触发
  getdata(true); // 传入 true 表示是刷新操作
  getuserordersum(); // 新增统计调用
};
const timemark = ref('');
const showPicker = ref(false);
const currentDate = ref([
  new Date().getFullYear().toString(),
  (new Date().getMonth() + 1).toString().padStart(2, '0'),
  new Date().getDate().toString().padStart(2, '0')
]);
const timekai = (type) => {
  timemark.value = type;
  showPicker.value = true;
};
const onConfirm = ({
                     selectedValues,
                     selectedOptions
                   }) => {
  currentDate.value = selectedValues;
  showPicker.value = false;
  // 身份证有效期
  if (timemark.value === 'startTime') {
    params.value.startTime = selectedValues.join('-');
  } else {
    params.value.endTime = selectedValues.join('-');
  }
  params.value.pages = 1;

  finished.value = false;
  loading.value = false;
  refreshing.value = true;
  error.value = false;

  // 直接调用 getdata，而不是等待列表自动触发
  getdata(true); // 传入 true 表示是刷新操作
  getuserordersum(); // 新增统计调用
}

// 退款
const refunds = (item) => {
  const id = {
    id: item.id
  }
  showConfirmDialog({
    title: '提示',
    message: '您确定要为该订单退款吗？',
  }).then(async () => {
    try {
      const response = await deviceRechargeRefund(id);
      if (response.status == 200) {
        showToast({
          type: 'success',
          message: '已成功为该订单退款',
          forbidClick: true,
          duration: 1000
        });
      } else {
        showToast({
          type: 'fail',
          message: response.desc || '退款失败',
          forbidClick: true,
          duration: 1000
        });
      }
    } catch (err) {
      showToast({
        type: 'fail',
        message: err.desc || '退款失败',
        forbidClick: true,
        duration: 1000
      });
    } finally {
      setTimeout(() => {
        onRefresh();
      }, 1000)
    }
  }).catch(() => {

  });
}
// 时间格式化工具函数
const formatISODate = (isoString) => {
  // 修复格式问题：将 "+0000" 转成 "+00:00"
  if (!isoString) return "-"; // 处理空值
  try {
    const fixedDateString = isoString.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
    const date = new Date(fixedDateString);
    // 转为本地时间并格式化为 "YYYY-MM-DD HH:mm:ss"
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      // second: "2-digit",
      hour12: false // 强制 24 小时制
    }).replace(/\//g, '-'); // 将斜杠替换为短横线（2025-02-23）
  } catch {
    return "-"; // 解析失败时返回占位符
  }
};
</script>

<style scoped lang="scss">
:deep(.van-dropdown-menu__bar) {
  box-shadow: none;

  .van-dropdown-menu__title {
    color: orange;
  }

  .van-dropdown-menu__title:after {
    border-color: transparent transparent orange orange;
  }
}

:deep(.searchBox) {
  background-color: white;

  .van-search {
    background-color: white;

    // 搜索框
    .van-search__content {
      background-color: white;
      border: 1px solid #cccccc;
      // border-radius: 5px;
      background-color: #f5f5f5;
    }
  }

  .van-search__action {
    color: #fff;
    background-color: #2FBC3C;
    border-radius: 16px;
    width: 40px;
    text-align: center;
    margin: 0 10px;
  }

  // 文字
  .search-confirm {
    display: flex;
    align-items: center;
    height: 100%;
    padding: 0 12px;

    .search-text {
      color: rgb(81, 164, 208);
      /* 蓝色搜索文字 */
      font-size: 14px;
      font-weight: 500;
      white-space: nowrap;
      cursor: pointer;
    }
  }
}

.topdropdown {
  position: relative;

  .dropdownLeft {
    position: absolute;
    bottom: 0;
    left: 16%;
    width: 20%;
    height: 3px;
    background-color: orange;
  }

  .dropdownRight {
    position: absolute;
    bottom: 0;
    right: 14%;
    width: 20%;
    height: 3px;
    background-color: orange;
  }
}

.flexbetween {
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: space-between;
}

.flexaround {
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: space-around;
}

.flex {
  display: flex;
  align-items: center;
  align-content: center;
}

.grid-content {
  // border: 1px solid #c1c5cd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  margin-top: 20px;
  background-color: white;

  .margin-t-0 {
    margin-top: 0;
  }

  .margin-b-0 {
    margin-bottom: 0;
  }

  .margin-b-12 {
    margin-bottom: 12px;
  }

  .hideText {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .storeZi {
    color: rgb(147, 147, 147);
    width: 50%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 12px;
  }

  .storeTitle {
    font-size: 14px;
    width: 70%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #000;
  }

  .grid-content-bottom {
    display: flex;
    align-items: center;
    align-content: center;
    justify-content: space-between;
    padding: 0 10px;
    width: 100%;
    font-size: 12px;
    color: rgb(81, 164, 208);
    box-sizing: border-box;
  }
}

.divider {
  width: 100%;
  height: 1px;
  border-bottom: 1px solid #c1c5cd;
}

.prompt {
  margin: 8px 0;
  text-align: center;
}

.condition {
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: space-around;
  gap: 10px;
  padding: 0 10px;
  box-sizing: border-box;

  .conditionLi {
    padding: 6px;
    border-radius: 8px;
    border: 1px solid #ddd;
    font-size: 12px;
    background-color: #FFF;
  }
}

.refund {
  font-size: 12px;
  color: #fff;
  background-color: #1989fa;
  text-align: center;
  cursor: pointer;
  height: 32px;
  padding: 0 12px;
  line-height: 1.2;
  border-radius: 4px;
  border: 1px solid #1989fa;
}

:deep(.van-field__control:read-only) {
  cursor: pointer;
}


.stats-tag {
  display: inline-flex;
  align-items: center;
  background: #f0faff;
  border: 1px solid #1989fa;
  border-radius: 16px;
  padding: 4px 12px;
  margin-right: 10px;
  font-size: 12px;

  .stats-label {
    color: #666;
    margin-right: 4px;
  }

  .stats-value {
    color: #1989fa;
    font-weight: 500;
  }
}

.condition2 {
  padding: 8px 15px;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
